//
//  HTHomeController.swift
//  WeiBoDemo
//
//  Created by 郝涛 on 16/4/16.
//  Copyright © 2016年 郝涛. All rights reserved.
//

import UIKit
private let HomeIdentifierId="HomeIdentifierIdaaaaar"
class HTHomeController: HTVisitorViewController {
    //数据
    var status:[HTStatus] = [HTStatus]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        //判断是否登录
        if isLogin == false {
            
            visitorView?.SetVisitorViewContent(nil, ImageName: nil)
        }
        setupTableViewInfo()
        
//        loadData {[weak self](statuss) -> () in
//            //赋值
//            self?.status = statuss
//            
//            //刷新UI
//            self?.tableView.reloadData()
//        }
        loadData(indicatorView.isAnimating())
    }
    //设置视图
    func setupUI(){
        
        navigationController!.view.insertSubview(showCountLabel, belowSubview: navigationController!.navigationBar)
        showCountLabel.frame = CGRect(x: 0, y: 64 , width: SCREENW, height: 34)
    }
    
    
    
    //设置tableview
    func setupTableViewInfo(){
        
        tableView.registerClass(HTStatusCell.self, forCellReuseIdentifier: HomeIdentifierId)
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        
        tableView.separatorStyle = .None
        
        tableView.tableFooterView = indicatorView
//添加下拉刷新控件
        tableView.addSubview(Refresh)
        
        
        
      Refresh.addTarget(self, action: "RefreshAction", forControlEvents: UIControlEvents.ValueChanged)
        
    }
    
   @objc func RefreshAction(){
//        print("开始刷新了")
     loadData(indicatorView.isAnimating())
    }
    
    //滚动到哪里
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == status.count - 1 && !indicatorView.isAnimating(){
            //开启
            indicatorView.startAnimating()
            //加载数据
            loadData(indicatorView.isAnimating())
        }

    }
    
    //懒加载控件
    private lazy var indicatorView :UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        
        view.color = UIColor.orangeColor()
        
        return view
    }()

 
    //自定义上拉刷新
    private lazy var Refresh :HTRefreshControl = HTRefreshControl()
    //显示多少条数据
    private lazy var showCountLabel :UILabel = {
        let lab = UILabel ()
        
        lab.textColor = UIColor.whiteColor()
        
        lab.font = UIFont.systemFontOfSize(16)
        
        lab.textAlignment = .Center
        
        lab.backgroundColor = UIColor.orangeColor()
        
        lab.text = "显示微博条数文字"
        lab.hidden = true
        
        return lab
    }()
    
}
extension HTHomeController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return status.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeIdentifierId, forIndexPath: indexPath)as!HTStatusCell
        //给cell传递数据
        cell.status = status[indexPath.row]
        
        
        return cell
    }
}
//请求微博首页数据

extension HTHomeController {
    
    func  loadData(isPullUp:Bool){
        
        var since_id :Int64 = 0
        var max_id :Int64 = 0
        
        //判断是否是上啦刷新
        if isPullUp{
            //true 上拉
            since_id = 0
            
            max_id = status.last?.id ?? 0
            //判断maxid如果不判断会返回重复的数据
            if max_id > 0{
                max_id -= 1
            }
 
        }else{//下拉
            since_id = status.first?.id ?? 0
            max_id = 0
            
        }
        
        HTNetworkTools.sharedNetworkTools.loadStatus(HTUserAccountTools.sharedTools.accessToken!, since_id: since_id, max_id: max_id) { (response, error) -> () in
            //停止动画
           self.endRefreshing()
            if error != nil{
                
                print(error)
                return
            }//判断数据是否存在
            guard let array = response?["statuses"] as?[[String:AnyObject]]else{
                print("返回的不是一个数组")
                return
            }
            
            //定义临时数组
            var tmpArray:[HTStatus] = [HTStatus]()
            //遍历数组转模型
            for dict in array{
                
                let status = HTStatus(dict: dict)
                tmpArray.append(status)
            }
            //判断上拉加载更多还是下拉
            if isPullUp{
                self.status = self.status + tmpArray
            }else{
                
                self.status = tmpArray + self.status
                
                // 如果我们showCountLabel 已经显示了 不应再执行动画了
                if self.showCountLabel.hidden == true{
                    self.setShowCountLabelAnim(tmpArray.count)
                }
            }
            // 刷新UI
            self.tableView.reloadData()
        }
     
        }
    //停止动画
    func endRefreshing(){
        self.indicatorView.stopAnimating()
     
        self.Refresh.endRefreshing()
    }
    //显示多少条数据label的动画
    func setShowCountLabelAnim(count:Int){
       self.showCountLabel.hidden = false
        
        var countString = ""
        
        if count == 0{
            countString = "您已经是最新的微博了"
        }else{
            countString = "您更新了\(count)条微博"
        }
        //设置内容
        showCountLabel.text = countString
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.showCountLabel.frame.origin.y = 64
            }) { (_) -> Void in
             UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                self.showCountLabel.frame.origin.y = 64 - 34
                }, completion: { (_) -> Void in
                    self.showCountLabel.hidden = true
             })
        }
        
    }
    
    
}




